package com.lujieni.test.testSelfAggrement;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.SQLOutput;
import java.util.List;

public class MyCodec extends ByteToMessageCodec<Message> {


    /**
     * 编码
     * @param ctx
     * @param msg
     * @param out
     */
    @Override
    protected void encode(ChannelHandlerContext ctx, Message msg, ByteBuf out) throws Exception {
        out.writeBytes(new byte[]{1, 2, 3, 4});
        out.writeByte(1); // 1:jdk序列化方式
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(msg);
        byte[] content = baos.toByteArray();
        out.writeInt(content.length);
        out.writeBytes(content);
    }

    /**
     * 解码
     * @param ctx
     * @param in
     * @param out
     */
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        int magic = in.readInt();
        byte serializerType = in.readByte();
        int contentLength = in.readInt();
        byte[] content = new byte[contentLength];
        in.readBytes(content);

        if (serializerType == 1) {
            ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(content));
            Message msg = (Message) ois.readObject();
            System.out.println(msg);
            out.add(msg);
        }
    }
}
